const {
	Service
} = require("uni-cloud-router");
const {
	httpClientCode
} = require("config");
const db = uniCloud.database();
const {
	checkToken
} = require('common-uni-id');
module.exports = class EntitlementService extends(
	Service
) {

	async get(event) {
		let response = {
			code: httpClientCode.ERROR.value,
			msg: '查询数据失败',
			data: null
		};
		let id = event.data.id
		if (!id) {
			id = 'e8d27cb364ed88d20020858878ba2980'
		}
		let taskInfoResult = await db.collection('wmz-entitlement').doc(id).get();
		taskInfoResult = taskInfoResult.data[0]
		// taskInfoResult.xieyiContent = taskInfoResult.xieyi
		if (taskInfoResult) {
			response.code = httpClientCode.SUCCESS.value;
			response.msg = '查询数据成功';
			response.data = taskInfoResult;
		}

		return response;
	}
	async buy(event) {
		let response = {
			code: httpClientCode.ERROR.value,
			msg: '购买失败',
			data: null
		};
		let userInfo
		const userRes = await checkToken(event.uniIdToken);
		if (userRes.userInfo) {
			userInfo = userRes.userInfo;
		}
		if (!userInfo || !userInfo.openid) {
			response.msg = '用户数据错误'
			return response
		}
		let id = event.data.id
		let phone = event.data.phone
		let orderId = event.data.orderId
		let finger = event.data.finger
		let channel = event.data.channel
		if (!id) {
			id = 'e8d27cb364ed88d20020858878ba2980'
		}
		let taskInfoResult = await db.collection('wmz-entitlement').doc(id).get();
		taskInfoResult = taskInfoResult.data[0]
		taskInfoResult.price = (taskInfoResult.price - Math.random() / 10).toFixed(2)
		let appletInfoData = await this.service.applet.getAppletInfoById(userInfo.app_id)
		if (!appletInfoData.balance || appletInfoData.balance < 10) {
			response.msg = '余额不足'
			return response
		}
		let res = await db.collection('wmz-entitlement-order').add({
			user_id: userInfo._id,
			entitlement_id: taskInfoResult._id,
			entitlement_name: taskInfoResult.name,
			create_time: new Date().getTime(),
			ali_user_id: userInfo.openid,
			status: '待付款',
			coupon_data: taskInfoResult.coupon_data,
			phone: phone,
			orderId: orderId,
			finger: finger,
			channel: channel,
			money: taskInfoResult.price,
			pla: 'wmz',
			shop_id: appletInfoData._id,
			app_id: appletInfoData._id,
			pay_app_id: appletInfoData.alipay.pay_app_id
		})
		if (!res.inserted) {
			response.msg = '新增订单数据失败'
			return response
		}
		if (finger.indexOf('userkey') > -1) {
			let plid = 0
			if (finger.indexOf('plid') > -1) {
				plid = finger.split('plid')[1]
				plid = plid.split('plid,')[0]
			}
			let url = 'https://game.adtianshi.cn/UrlCenter/Transfer?plid=' + plid
			let userkey = ""
			if (finger.indexOf('userkey') > -1) {
				userkey = finger.split('userkey')[1]
				userkey = userkey.split('userkey,')[0]
				url += "&userkey=" + userkey
			}
			url += "&type=1"
			let adtianshiRes = await uniCloud.httpclient.request(url, {
				method: 'GET',
				dataType: 'json' // 此处指定为json表示将此请求的返回值解析为json
			})
			await db.collection('wmz-advertiser').add({
				"url": url,
				"res": adtianshiRes
			})
		}
		res = await this.service.alipay.pay(userInfo.app_id, userInfo.openid, res.id, taskInfoResult.price *
			100,
			'开通会员', '/notify-entitlement/alipay')
		if (res) {
			response.code = httpClientCode.SUCCESS.value;
			response.msg = '查询数据成功';
			response.data = {
				trade_no: res.data
			};
		}
		return response;
	}

	async list(event) {
		let response = {
			code: httpClientCode.ERROR.value,
			msg: '查询数据失败',
			data: null
		};
		let userInfo
		const userRes = await checkToken(event.uniIdToken);
		if (userRes.userInfo) {
			userInfo = userRes.userInfo;
		}
		if (!userInfo || !userInfo.openid) {
			response.msg = '用户数据错误'
			return response
		}
		let data = event.data
		let appletInfo = await db.collection('wmz-applet-info').doc(userInfo.app_id).get()
		appletInfo = appletInfo.data[0]
		let app_id = userInfo.app_id
		if (appletInfo.p_app_id) {
			app_id = appletInfo.p_app_id
		}
		let order = await db.collection('wmz-entitlement-order').where({
				ali_user_id: userInfo.openid,
				app_id: app_id,
				status: '已付款'
			}).skip(data.skip)
			.limit(data.limit).orderBy('create_time', 'desc').get();
		response.code = httpClientCode.SUCCESS.value;
		response.msg = '查询数据成功';
		response.data = order.data;

		appletInfo = await db.collection('wmz-applet-info').doc(app_id).get()
		appletInfo = appletInfo.data[0]
		if (appletInfo) {
			response.phone = appletInfo.phone;
		}
		return response;
	}
	async coupon(event) {
		let response = {
			code: httpClientCode.ERROR.value,
			msg: '查询数据失败',
			data: null
		};
		let userInfo
		const userRes = await checkToken(event.uniIdToken);
		if (userRes.userInfo) {
			userInfo = userRes.userInfo;
		}
		if (!userInfo || !userInfo.openid) {
			response.msg = '用户数据错误'
			return response
		}
		let data = event.data
		let appletInfo = await db.collection('wmz-applet-info').doc(userInfo.app_id).get()
		appletInfo = appletInfo.data[0]
		let app_id = userInfo.app_id
		if (appletInfo.p_app_id) {
			app_id = appletInfo.p_app_id
		}
		let order = await db.collection('wmz-entitlement-coupon').where({
			ali_user_id: userInfo.openid,
			app_id: app_id,
			status: '未使用'
		}).orderBy('money', 'asc').get();
		response.code = httpClientCode.SUCCESS.value;
		response.msg = '查询数据成功';
		response.data = order.data;
		return response;
	}

	async recharge(event) {
		let response = {
			code: httpClientCode.ERROR.value,
			msg: '购买失败',
			data: null
		};
		/* let userInfo
		const userRes = await checkToken(event.uniIdToken);
		if (userRes.userInfo) {
			userInfo = userRes.userInfo;
		}
		if (!userInfo || !userInfo.openid) {
			response.msg = '用户数据错误'
			return response
		} */
		let coupon_id = event.data.coupon_id
		let mobile = event.data.mobile
		let moneyVal = event.data.moneyVal

		let coupon = await db.collection('wmz-entitlement-coupon').doc(coupon_id).get();
		coupon = coupon.data[0]
		if (!coupon) {
			response.msg = '优惠券错误'
			return response
		}
		if (moneyVal < coupon.user_money) {
			response.msg = '该优惠券大于' + coupon.user_money + "可用"
			return response
		}
		let money = moneyVal - coupon.money
		money = money.toFixed(2)
		money = (money - Math.random() / 10).toFixed(2)
		let appletInfoData = await this.service.applet.getAppletInfoById(coupon.app_id)
		let res = await db.collection('wmz-entitlement-recharge').add({
			user_id: coupon.user_id,
			create_time: new Date().getTime(),
			ali_user_id: coupon.ali_user_id,
			status: '待付款',
			coupon_id: coupon_id,
			money: money,
			total_money: moneyVal,
			coupon_money: coupon.money,
			mobile: mobile,
			pla: 'wmz',
			shop_id: coupon.app_id,
			app_id: coupon.app_id,
			pay_app_id: appletInfoData.alipay.pay_app_id
		})
		if (!res.inserted) {
			response.msg = '新增订单数据失败'
			return response
		}
		res = await this.service.alipay.pay(coupon.app_id, coupon.ali_user_id, res.id, money * 100,
			mobile + '充值', '/notify-entirecharge/alipay', true)
		if (res) {
			response.code = httpClientCode.SUCCESS.value;
			response.msg = '查询数据成功';
			response.data = {
				trade_no: res.data
			};
		}
		return response;
	}


	async recharge_app(event) {
		let response = {
			code: httpClientCode.ERROR.value,
			msg: '购买失败',
			data: null
		};
		let userInfo
		const userRes = await checkToken(event.uniIdToken);
		if (userRes.userInfo) {
			userInfo = userRes.userInfo;
		}
		userInfo.app_id='41d77edc652531e2064b65687de0a691'
		/* if (!userInfo || !userInfo.openid) {
			response.msg = '用户数据错误'
			return response
		} */
		console.log(event.data)
		let goods_type = event.data.goods_type
		let coupon_id = event.data.coupon_id
		let mobile = event.data.mobile
		let moneyVal = event.data.moneyVal
		let entitlement_id = event.data.entitlement_id
		let res
		if (goods_type === 'mobile_coupon') {
			let taskInfoResult = await db.collection('wmz-entitlement').doc(entitlement_id).get();
			taskInfoResult = taskInfoResult.data[0]
			taskInfoResult.price = (taskInfoResult.price - Math.random() / 10).toFixed(2)
			let appletInfoData = await this.service.applet.getAppletInfoById(userInfo.app_id)
			res = await db.collection('wmz-entitlement-order').add({
				goods_type: goods_type,
				user_id: userInfo._id,
				entitlement_id: taskInfoResult._id,
				entitlement_name: taskInfoResult.name,
				create_time: new Date().getTime(),
				ali_user_id: userInfo.openid,
				status: '待付款',
				coupon_data: taskInfoResult.coupon_data,
				phone: userInfo.username,
				money: taskInfoResult.price,
				pla: 'app',
				shop_id: "41d77edc652531e2064b65687de0a691",//appletInfoData._id
				app_id: "41d77edc652531e2064b65687de0a691",
				pay_app_id: appletInfoData.alipay.pay_app_id
			})
			if (!res.inserted) {
				response.msg = '新增订单数据失败'
				return response
			}
			/* res = await this.service.alipay.pay(userInfo.app_id, userInfo.openid, res.id, taskInfoResult.price *
				100,
				'购买卡券', '/notify-entitlement/alipay') */

			res = await this.service.alipay.payApp(userInfo.app_id, userInfo.openid, res.id, taskInfoResult
				.price *
				100,
				'开通会员', '/notify-entitlement/alipay')
			if (res) {
				response.code = httpClientCode.SUCCESS.value;
				response.msg = '查询数据成功';
				response.data = {
					trade_no: res.data
				};
			}
		} else {
			let coupon = await db.collection('wmzmall-marketing-coupon').doc(coupon_id).get();
			coupon = coupon.data[0]
			if (!coupon) {
				response.msg = '优惠券错误'
				return response
			}
			/* if (moneyVal < coupon.user_money) {
				response.msg = '该优惠券大于' + coupon.user_money + "可用"
				return response
			} */
			let money = moneyVal - coupon.price/100
			// money = money.toFixed(2)
			// money = (money - Math.random() / 10).toFixed(2)
			let appletInfoData = await this.service.applet.getAppletInfoById(userInfo.app_id)
			res = await db.collection('wmz-entitlement-recharge').add({
				user_id: userInfo._id,
				create_time: new Date().getTime(),
				status: '待付款',
				coupon_id: coupon_id,
				money: money,
				total_money: moneyVal,
				coupon_money: coupon.price/100,
				mobile: mobile,
				pla: 'wmz',
				shop_id: userInfo.app_id,
				app_id: userInfo.app_id,
				pay_app_id: appletInfoData.alipay.pay_app_id
			})
			if (!res.inserted) {
				response.msg = '新增订单数据失败'
				return response
			}
			res = await this.service.alipay.payApp(coupon.app_id, coupon.ali_user_id, res.id, money * 100,
				'充值', '/notify-entirecharge/alipay', true)
		}
		if (res) {
			response.code = httpClientCode.SUCCESS.value;
			response.msg = '查询数据成功';
			response.data = {
				trade_no: res.data
			};
		}
		return response;
	}

	async rechargeList(event) {
		let response = {
			code: httpClientCode.ERROR.value,
			msg: '查询数据失败',
			data: null
		};
		let userInfo
		const userRes = await checkToken(event.uniIdToken);
		if (userRes.userInfo) {
			userInfo = userRes.userInfo;
		}
		if (!userInfo || !userInfo.openid) {
			response.msg = '用户数据错误'
			return response
		}
		let data = event.data
		let appletInfo = await db.collection('wmz-applet-info').doc(userInfo.app_id).get()
		appletInfo = appletInfo.data[0]
		let app_id = userInfo.app_id
		if (appletInfo.p_app_id) {
			app_id = appletInfo.p_app_id
		}
		let order = await db.collection('wmz-entitlement-recharge').where({
				ali_user_id: userInfo.openid,
				app_id: app_id,
				status: '已付款'
			}).skip(data.skip)
			.limit(data.limit).orderBy('create_time', 'desc').get();
		response.code = httpClientCode.SUCCESS.value;
		response.msg = '查询数据成功';
		response.data = order.data;
		return response;
	}
	async aftersale(event) {
		let response = {
			code: httpClientCode.ERROR.value,
			msg: '提交失败',
			data: null
		};
		let userInfo
		const userRes = await checkToken(event.uniIdToken);
		if (userRes.userInfo) {
			userInfo = userRes.userInfo;
		}
		if (!userInfo || !userInfo.openid) {
			response.msg = '用户数据错误'
			return response
		}
		let data = event.data
		data.user_id = userInfo._id
		data.create_time = new Date().getTime()
		let order = await db.collection('wmz-entitlement-aftersale').add(data)
		response.code = httpClientCode.SUCCESS.value;
		response.msg = '提交成功';
		response.data = order.data;
		return response;
	}

	async getAppkey(event) {
		return "BC-9474612f59bc4911a19a5f2d935d2ee0";
	}


};